﻿namespace Digitalmes.Common.Utils;

/// <summary>
/// 系统Shell命令
/// </summary>
public static class ShellUtil
{
    /// <summary>
    /// Bash 命令
    /// </summary>
    /// <param name="command">命令参数</param>
    /// <returns></returns>
    public static string Bash(string command)
    {
        var escapedArgs = command.Replace("\"", "\\\"");
        var process = new Process()
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = "/bin/bash",
                Arguments = $"-c \"{escapedArgs}\"",
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true,
            }
        };
        process.Start();
        var result = process.StandardOutput.ReadToEnd();
        process.WaitForExit();
        process.Dispose();
        return result;
    }

    /// <summary>
    /// cmd命令
    /// </summary>
    /// <param name="fileName">可执行文件</param>
    /// <param name="args">命令参数</param>
    /// <returns></returns>
    public static string Cmd(string fileName, string args)
    {
        var info = new ProcessStartInfo
        {
            FileName = fileName,
            Arguments = args,
            RedirectStandardOutput = true
        };

        using var process = Process.Start(info);
        if (process != null)
            return process.StandardOutput.ReadToEnd();

        return "";
    }
}
